package interpreter.debugger.ui;

import interpreter.debugger.DebugVirtualMachine;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;

/**
 * Displays current function
 * 
 * @author Kris Selbekk
 */
public class DisplaySrcCommand extends Command {
    private Vector<String> source;

    // Extends original initializer
    public void init(DebugVirtualMachine dvm) {
        super.init( dvm );
        source = new Vector<String>();
    }

    /**
     * Loads the source from file
     */
    public void exec( String[] args ) {
        try {
            BufferedReader srcFile = new BufferedReader( new FileReader( dvm.getFilePath() + ".x" ));
            source = new Vector<String>();

            for( int lineNo = 1; srcFile.ready(); lineNo++ ) {
                source.add(String.format("%3d. %s", lineNo, srcFile.readLine() ));
            }

        } catch( FileNotFoundException fnf ) {
            System.err.println("Error: File was not found.");
            System.exit(-1);
        } catch( IOException io ) {
            System.err.println("Error: IOException caught");
            System.exit(-1);
        }
    }

    /**
     * Prints out the source code
     */
    public void print() {
        // Preliminary printouts
        System.out.println("-------");

        // Loops through each line of source
        int lineNo = 1;
        for( String line : source ) {
            // If breakpoint is set, mark them
            if( dvm.isBreakpoint(lineNo)) line = "**" + line;
            else line = "  " + line;

            // Marks current line
            if( lineNo == dvm.getCurrentLine() ) line += "\t\t\t<----- ";

            // Prints the line itself and updates line number
            System.out.println(line);
            lineNo++;
        }
    }
}
